package com.wechat.service;

import java.sql.Timestamp;
import java.util.Map;

import org.sword.wechat4j.token.TokenProxy;

import tool.JsonTool;

import com.base.bean.Wechat;
import com.base.dao.WechatDao;
import com.base.dao._BaseDao;

public class WechatService {

	/** 微信工具类 用单例模式
	 *  主要功能：
	 *  由URL生成wx.config注入对象（110分钟有效，失效则自动刷新数据库中对应的jsapi_ticket  access_token）
	 *  
	 *  明天再测试下：
	 *  主方法如下： 生成注入对象： 
	 *  public String wxConfig(String url)
	 * @param args
	 */
	
	//单例模式 start
	private volatile static WechatService instance = null;
	private static WechatDao wechatDao;
	
	private WechatService() {
		wechatDao = (WechatDao)_BaseDao.ac.getBean("WechatDao");
	}
	public static WechatService getInstance() {
		if (instance == null) {
			synchronized (WechatService.class) {// 1
				if (instance == null) {// 2
					instance = new WechatService();// 3
					
				}
			}
		}
		return instance;
	}
	//单例模式 end
	

	//找到或者更新jsapi_ticket
	public Wechat find(){
		Wechat wechat= wechatDao.findByHql("from Wechat w where w.weid=1").get(0);
		if(System.currentTimeMillis()>wechat.getExpire()){
			return update(wechat);
		}else
			return wechat;
	}
	

	
	//生成注入对象
	public String wxConfig(String url){
		StringBuffer sb=new StringBuffer();
		
		Wechat wechat=find();
		Map map=Sign.sign(wechat.getJsapiTicket(), url);
		sb.append("wx.config({debug: false,appId: '");
		sb.append(wechat.getOpenId()+"',timestamp:");
		sb.append((String) map.get("timestamp")+",nonceStr:'");
		sb.append((String)map.get("nonceStr")+"',signature:'");
		sb.append((String)map.get("signature"));
		sb.append("',jsApiList:['checkJsApi','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ'," +
				"'onMenuShareWeibo','hideMenuItems','showMenuItems','hideAllNonBaseMenuItem','showAllNonBaseMenuItem'," +
				"'translateVoice','startRecord','stopRecord','onRecordEnd','playVoice','pauseVoice','stopVoice','uploadVoice'," +
				"'downloadVoice','chooseImage','previewImage','uploadImage','downloadImage','getNetworkType','openLocation'," +
				"'getLocation','hideOptionMenu','showOptionMenu','closeWindow','scanQRCode','chooseWXPay','openProductSpecificView'," +
				"'addCard','chooseCard','openCard']});");
	
		return sb.toString();

	}
	
	
	
	private Wechat update(Wechat wechat){
		wechat.setJsapiTicket(getJsapiTicket());
		wechat.setAccessToken(getAccessToken());
		wechat.setExpire(System.currentTimeMillis()+1000*60*110);	//110分钟后
		wechatDao.merge(wechat);
		return wechat;
	}
	
	//生成签名
	private Map<String,String> sign(String jsapi_ticket, String url){
		return Sign.sign(jsapi_ticket, url);
	}
	
	private String getJsapiTicket(){
		
		return TokenProxy.jsApiTicket();
	}
	
	private String getAccessToken(){
		return TokenProxy.accessToken();
	}
	
	
	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Wechat w=WechatService.getInstance().find();
		System.out.println(w.getAccessToken());
		System.out.println(w.getJsapiTicket());
		System.out.println(w.getExpire());
		Timestamp time=new Timestamp(w.getExpire());
		System.out.println("time:"+time);
		
		//String wxConfig=WechatService.getInstance().wxConfig("http://we.51waji.com/microhifo/gps_test.jsp");
		//System.out.println(wxConfig);
		

	}

}
